<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"/>
  <title></title>
  <link rel="StyleSheet" href="../approver/css/dtree.css" type="text/css"/>
  <link rel="stylesheet" type="text/css" href="../approver/css/zTreeStyle.css"/>
  <script src="../approver/js/jquery.min.js"></script>
  <script src="../js/jquery.base64.js"></script>
  <script src="../approver/js/jquery-1.11.1.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="../approver/js/jquery.fastLiveFilter.js" type="text/javascript" charset="utf-8"></script>
  <script src="../approver/js/jquery.ztree.core-3.5.js" type="text/javascript" charset="utf-8"></script>
  <script src="../approver/js/jquery.ztree.excheck-3.5.js" type="text/javascript" charset="utf-8"></script>
  <script src="../approver/js/jquery.ztree.exhide.js" type="text/javascript" charset="utf-8"></script>
  <script src="../approver/js/fuzzysearch.js" type="text/javascript" charset="utf-8"></script>
  <script src="../approver/js/jquery.fastLiveFilter.js" type="text/javascript" charset="utf-8"></script>
  <style type="text/css">
    body,
    html {
      padding: 0;
      margin: 0;
      width: 100%;
      font: 14px Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial, sans-serif;
      background: #FFF;

    }

    .chat_choice {
      border-bottom: 1px solid #e0e0e0;
      display: flex;
    }

    .chat_content {
      border-bottom: 1px solid #e0e0e0;
    }

    li {
      list-style: none;
    }

    .groupChat {
      width: 100%;

    }

    .selectorResult {
      border: 1px solid #eee;
      min-height: 30px;
      width: calc(100% - 130px);
      float: right;
      border-radius: 5px;
      padding: 5px;
      position: relative;
      margin: 10px;
    }

    .chat_top {
      width: 100px;
      font-size: 15px;
      color: #666;
      font-weight: bold;
      float: left;
      padding-left: 10px;
      line-height: 300px;
      background: #F3F3F3;
    }

    input.shuru {
      height: 30px;
      width: 300px;
      margin: 5px auto;
      padding: 0 5px;
      color: #7a7171;
      border-radius: 4px;
      border: 1px solid #C9C9C9;
      margin-top: 15px;
    }

    .chat_content {
      height: calc(100% - 50px);
      width: 100%;
      overflow: auto;
    position: fixed;
    }

    .choice_radio {
      height: 80px;
      width: 100%;
      border-bottom: 1px dotted #e2e2e2;
      padding-top: 15px;
    }

    .input-row {
      padding-left: 15px;
      margin-bottom: 10px;
    }

    .customGroup,
    .projectGroup {
      padding: 20px;
      height: calc(100% - 240px);
      overflow: auto;
    }

    .projectGroup ul li {
      cursor: pointer;
      padding-bottom: 10px;
    }

    .screening {
      height: 25px;
      width: 40%;
      margin: 5px auto;
      padding: 0 5px;
      color: #7a7171;
      border-radius: 4px;
      border: 1px solid #C9C9C9;
      margin-left: 10px;
      display: none;
    }

    .saveBtn {
      float: right;
      height: 28px;
      line-height: 28px;
      margin: 15px 15px 0;
      padding: 0 15px;
      border: 1px solid #b64545;
      background-color: #b64545;
      color: #fff;
      border-radius: 2px;
      font-weight: 400;
      cursor: pointer;
    }

    .treeDiv {
      position: fixed;
      background: rgba(0, 0, 0, .25);
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      display: none;
      z-index: 9;
    }

    .dtree {
      background: #fff;
      width: 40%;
      height: 60%;
      overflow-y: hidden;
      position: absolute;
      top: 20%;
      left: 30%;
      border-radius: 10px;
      padding: 10px;
    }

    .max {
      background: url(../approver/img/max.png) no-repeat center;
      background-size: contain;
      position: absolute;
      bottom: 5px;
      right: 5px;
      height: 20px;
      width: 20px;
      cursor: pointer;
    }

    .ztree {

      height: calc(100% - 40px);
      overflow: auto;
    }

    .btn {
      text-align: right;
      padding-right: 10px;
    }

    .btn button {

    }

    .saveIcon {
      display: inline-block;
      line-height: 1;
      white-space: nowrap;
      cursor: pointer;
      -webkit-appearance: none;
      text-align: center;
      box-sizing: border-box;
      outline: none;
      margin: 0;
      transition: .1s;
      font-weight: 500;
      -moz-user-select: none;
      -webkit-user-select: none;
      -ms-user-select: none;
      padding: 7px 15px;
      font-size: 14px;
      border-radius: 4px;
      color: #fff;
      background-color: #409eff;
      border: 1px solid #409eff;
      position: absolute;
      right: 10px;
      bottom: 10px;
    }

    .textareaDiv {
      border: 1px solid #eee;
      min-height: 60px;
      width: calc(100% - 35px);
      border-radius: 5px;
      padding: 5px;
      margin: 10px;
    }
  </style>

</head>
<body>
<div class="groupChat">

  <div class="chat_content">

    <!--用户选择-->
    <div class="treeDiv" id="file_div">
      <div class="dtree">
        关键字：<input type="text" id="key" value="" class="empty" placeholder="请输入关键字"/>
        <ul id="file_tree" class="ztree" style="height: calc(100% - 50px);"></ul>
        <div class="btn">
          <button class="cancel" onclick="treeDivHide('file_div', 'file_tree')">保存</button>
        </div>
      </div>
    </div>

    <div class="chat_choice">
      <div class="chat_top">
        必填附件
      </div>
      <div class="selectorResult">

        <ul id="file_tree_select" class="ulSelected">

        </ul>
        <i class="max" onclick="treeDivShow('file_div')"></i>
      </div>
    </div>


  </div>


  <button class="saveIcon" onclick="saveData()">保存</button>
</div>

<script type="text/javascript">

  (
    function (open) {
      XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
        open.call(this, method, url, async, user, pass);//this指XMLHttpRequest
        this.setRequestHeader("Authorization", window.parent.getToken());//mounted时传入的
      }
    }
  )(XMLHttpRequest.prototype.open)


  $(window).resize(function () {
    $('.selectorResult').each(function () {
      $(this).prev().css({
        'height': $(this).height() + 32 + 'px',
        'line-height': $(this).height() + 32 + 'px',
      })
    })
  });
  $(function () {
    $('.selectorResult').each(function () {
      $(this).prev().css({
        'height': $(this).height() + 32 + 'px',
        'line-height': $(this).height() + 32 + 'px',
      })
    })
    // $('#search_input').fastLiveFilter('#search_list');


  })

  //树形选择展示
  function treeDivShow(treeDiv) {
    $('#' + treeDiv).show();
  }

  //树形选择隐藏
  function treeDivHide(treeDiv, treeId) {
    treeOnCheck(treeId)
    $('#' + treeDiv).hide();
    // var searchInput = $('#key');
    // searchInput.val('').blur();//清空模糊搜索绑定的input
    // var event = new UIEvent('input');// 构造input事件对象
    // searchInput[0].dispatchEvent(event);// 触发input的input事件
  }
  function delKey(key, id) {
    // console.log(key, id)
    $("#" + id).parent().remove()
    var zTree = $.fn.zTree.getZTreeObj(key);
    var nodes = zTree.getCheckedNodes(true);
    for(var k=0;k<nodes.length;k++){
      if(nodes[k].id==id){
        zTree.checkNode(nodes[k]);//取消这个节点的勾选状态
      }
    }
  }

  //节点点击事件
  function treeOnCheck(treeId) {
    setTimeout(() => {
      var nodes = $("#" + treeId).find(".checkbox_true_full")
      console.log("选中节点")
      console.log(nodes)
      var str = '';
      for (var i = 0, l = nodes.length; i < l; i++) {

        var id = nodes[i].dataset.id

        var key = nodes[i].dataset.name
          // console.log(nodes[i])
          str += '<li id="' + treeId + '_' + key + '"><input type="hidden" name="' + treeId + '_key" value="' + id + '" />' + key
          str += "<i class='del' id='" + id + "' onclick=\"delKey('" + treeId + "','" + id + "')\">×</i>"
          str += '</li>'

      }
      // console.log(str)
      $("#" + treeId + "_select").html(str);
    }, 500);
  }

  // 页面执行完初始化数据
  $(document).ready(function () {

    // 获取待选数据
    getDirData();

    // 查询之前选择的数据
    getSelectedData();



  });


  //部门树形结构配置
  var setting = {
    check: {
      enable: true,
      chkboxType: {"Y": "s", "N": "s"}
    },
    data: {
      simpleData: {
        enable: true
      }
    },
    view: {
      addDiyDom: addDiyDom,
    },
    callback: {
      // onCheck: treeOnCheck
    }
  };
  function addDiyDom(treeId, treeNode) {
    $('#' + treeNode.tId + '_check').attr({'data-id': treeNode.key, 'data-name': treeNode.name })
  }

  function getChildrenAndDescendants(treeData, parentId) {
    let result = [];

    // 遍历当前级别的节点
    for (let i = 0; i < treeData.length; i++) {
      const node = treeData[i];

      // 如果当前节点的parentId与指定的parentId匹配，则将其添加到结果中
      if (node.pId === parentId) {
        result.push(node);

        // 递归获取当前节点的所有子节点
        const children = getChildrenAndDescendants(treeData, node.id);
        if (children.length > 0) {
          result = result.concat(children); // 合并子节点到结果中
        }
      }
    }

    return result;
  }


  //获取用户数据
  function getDirData() {
    $.ajax({
      url: window.parent.getBackUrl() + "/folder/findAll",
      dataType: 'json',
      type: "GET",
      async: false,
      cache: false,
      success: function (data) {

        var treeData = getChildrenAndDescendants(data.data,'0')


        $.fn.zTree.init($("#file_tree"), setting, treeData);
        var treeObj = $.fn.zTree.init($("#file_tree"), setting, treeData);
        treeObj.expandAll(true);
        setTimeout(() => {
          treeObj.expandAll(false);
        }, 10);
        fuzzySearch('file_tree','#key',null,true); //初始化模糊搜索方法
      }
    });

  }



  /**
   * 保存数据
   */
  function saveData() {
    // 向后台发送的数据
    var reqData = {};

    // 节点唯一标识
    var actUuid = getUrlParam("actUuid");
    reqData.actUuid = actUuid;


    // 用户已选数据
    var requiredFile = getDataList('file_tree_key');
    reqData.requiredFile = requiredFile;


    $.ajax({
      url: window.parent.getBackUrl() + "/wf/fileBase/saveRequiredFile",
      dataType: 'json',
      type: "POST",
      data: {data: baseL('encode', JSON.stringify(reqData))},
      cache: false,
      success: function (data) {
        window.parent.layer.msg("保存成功")
        window.parent.closeLayer();
      }
    });


  }

  //获取url传过来的参数
  function getUrlParam(name) { //封装方法
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
  }

  //获取数据集合
  function getDataList(name) {
    var dataList = $("input[name='" + name + "']");
    var dataKeyList = [];
    for (var i = 0; i < dataList.length; i++) {
      dataKeyList[i] = $(dataList[i]).val();
    }
    return dataKeyList;
  }



  //获取已经选择的数据
  function getSelectedData() {
    //节点唯一标识
    var actUuid = getUrlParam('actUuid');
    $.ajax({
      url: window.parent.getBackUrl() + "/wf/fileBase/getRequiredFile?actUuid=" + actUuid,
      dataType: 'json',
      type: "GET",
      cache: false,
      success: function (res) {

        if (res.data != null && res.data.requiredFile != null) {
          for (var i = 0; i < res.data.requiredFile.length; i++) {
            writeSelectedData(res.data.requiredFile[i]);
          }
        }
        // for (var i = 0; i < data.rows.length; i++) {
        //   writeSelectedData(data.rows[i]);
        // }
      }
    });

  }




  /**
   * 根据tree标识和审批人标识获取审批人显示名称
   * @param treeKey
   * @param approver
   */
  function getShowName(treeId, approver) {
    var zTree = $.fn.zTree.getZTreeObj(treeId);
    var nodes = zTree.getNodes();
    var node = zTree.getNodeByParam('key', approver);
    if (node != null) {
      // console.log(node)
      zTree.checkNode(node, true, true);
    }
    return node != null ? node : "未找到配置项";
  }

  //写入已选择的数据
  function writeSelectedData(data) {
     var type = 'file'

    var dataHtml = "";
    dataHtml += '<li id="' + type + '_tree_' + data + '">';
    dataHtml += '<input type="hidden" name="' + type + '_tree_key" value="' + data + '" />';
    dataHtml += getShowName(type + '_tree', data).name;
    dataHtml += "<i class='del' id='" + getShowName(type + '_tree', data).id + "' onclick=\"delKey('" + type + '_tree' + "','" + getShowName(type + '_tree', data).id + "')\">×</i>"
    dataHtml += '</li>'

    $("#file_tree_select").append(dataHtml);

  }

</script>


</body>
</html>
